const BASE_URL = import.meta.env.VITE_DIFY_BASE // https://api.dify.example
const API_KEY = import.meta.env.VITE_DIFY_KEY // app-xxx

// utils/dify/dify.ts
export async function* chatStream(inputs: any, conversationId = '', user = 'demo', signal?: AbortSignal) {
  const res = await fetch(`${BASE_URL}/v1/chat-messages`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      inputs,
      query: inputs.question,
      response_mode: 'streaming',
      conversation_id: conversationId,
      user,
    }),
    signal, // 外部可中断
  })

  if (!res.ok) throw new Error(await res.text())
  if (!res.body) return

  const reader = res.body.getReader()
  const decoder = new TextDecoder()
  let buf = ''
  let think = ''
  let answer = ''
  let thinking = false
  while (true) {
    const { done, value } = await reader.read()
    if (done) break
    buf += decoder.decode(value, { stream: true })
    const lines = buf.split('\n')
    buf = String(lines.pop())

    for (const line of lines) {
      if (!line.startsWith('data:')) continue
      const data = JSON.parse(line.slice(5))
      if (data.event !== 'message') continue

      const chunk = data.answer ?? ''
      const full = think + answer + chunk

      if (full.includes('<think>')) {
        thinking = true
        continue
      }
      if (full.includes('</think>')) {
        thinking = false
        continue
      }
      if (thinking) {
        think += chunk
      } else {
        answer += chunk
      }
      yield { done: false, think, answer }
    }
  }
  yield { done: true, think, answer }
}
